package com.yuanian.timingwheel.annotation.scan;

import com.yuanian.timingwheel.annotation.TimingTask;
import com.yuanian.timingwheel.annotation.TimingTaskAnnoHandler;
import com.yuanian.timingwheel.annotation.TimingTaskType;
import com.yuanian.timingwheel.context.SpringContext;
import com.yuanian.timingwheel.infrastructure.AopTargetUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 自动任务扫描器
 */
public class TimingTaskScanner extends TimingTaskAnnoHandler {

    public void scan() throws Exception {
        //获取Component和Service注解的类
        Map<String, Object> map = new HashMap<>();
        map.putAll(SpringContext.getBeansWithAnnotation(Component.class));
        map.putAll(SpringContext.getBeansWithAnnotation(Service.class));
        //遍历类
        for (Map.Entry entry : map.entrySet()) {
            //获取动态代理的原对象
            Object obj = AopTargetUtils.getTarget(entry.getValue());
            Class clz = obj.getClass();
            Method[] methods = clz.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(TimingTask.class)) {
                    TimingTask timingTask = method.getAnnotation(TimingTask.class);
                    if (timingTask.timingTaskType() == TimingTaskType.AUTO) {//自动任务
                        //获取动态参数解析器
                        String dynamicParamSolver = timingTask.dynamicParamSolver();
                        handle(dynamicParamSolver, clz, method, obj, null);
                    }
                }
            }
        }
    }

}
